from flask import Blueprint, render_template, current_app, jsonify
from app.models import Video
from app.utils.mime_types import get_mime_type
from app.utils.video_processor import process_video_url
import time

main = Blueprint('main', __name__)

@main.route('/')
def index():
    try:
        # 获取已发布的视频
        videos = Video.query.filter_by(status='published')\
                          .order_by(Video.created_at.desc())\
                          .all()
        
        base_domain = current_app.config['QINIU_DOMAIN']
        
        # 处理视频数据
        processed_videos = []
        for video in videos:
            video_data = {
                'id': video.id,
                'title': video.title,
                'description': video.description or '',
                'cover_url': process_video_url(video.cover_url, base_domain, 'covers'),
                'video_url': process_video_url(video.video_url, base_domain, 'videos'),
                'category': video.category.name if video.category else '暂无分类',
                'views': video.views or 0,
                'created_at': video.created_at.strftime('%m-%d') if video.created_at else '',
            }
            processed_videos.append(video_data)
            
        current_app.logger.info(f"Successfully loaded {len(processed_videos)} videos")
        return render_template('main/index.html', videos=processed_videos)
        
    except Exception as e:
        current_app.logger.error(f"Error loading videos: {str(e)}")
        return render_template('error.html', error="加载视频失败，请稍后重试"), 500

@main.route('/video/<int:video_id>/preview')
def preview_video(video_id):
    try:
        video = Video.query.get_or_404(video_id)
        base_domain = current_app.config['QINIU_DOMAIN']
        
        # 处理视频和封面URL
        video_url = process_video_url(video.video_url, base_domain, 'videos')
        cover_url = process_video_url(video.cover_url, base_domain, 'covers')
        
        # 添加时间戳防止缓存
        timestamp = int(time.time())
        video_url = f"{video_url}?t={timestamp}"
        cover_url = f"{cover_url}?t={timestamp}"
        
        # 获取视频类型
        ext = video.video_url.split('.')[-1].lower() if '.' in video.video_url else 'mp4'
        
        return jsonify({
            'success': True,
            'video_url': video_url,
            'cover_url': cover_url,
            'title': video.title,
            'mime_type': get_mime_type(ext),
            'download_url': video_url
        })
        
    except Exception as e:
        current_app.logger.error(f"Error previewing video {video_id}: {str(e)}")
        return jsonify({
            'success': False,
            'error': '获取视频信息失败'
        }), 500